<template>
  <div class="asset-edit">
    <!-- 欢迎页面 - 当没有ID参数时显示 -->
    <div v-if="!hasId" class="welcome-page">
      <!-- 快速访问区域 -->
      <div class="quick-access-section">
        <el-card class="access-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>快速编辑资产</span>
              <el-tag type="info" size="small">输入ID或名称快速跳转到资产编辑</el-tag>
            </div>
          </template>
          
          <div class="access-content">
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="access-item">
                  <label>按ID编辑：</label>
                  <el-input
                    v-model="accessId"
                    placeholder="请输入资产ID"
                    clearable
                    @keyup.enter="accessById"
                    @clear="clearAccess"
                  >
                    <template #append>
                      <el-button @click="accessById" :loading="accessing">
                        <el-icon><Edit /></el-icon>
                      </el-button>
                    </template>
                  </el-input>
                </div>
              </el-col>
              
              <el-col :span="8">
                <div class="access-item">
                  <label>按名称编辑：</label>
                  <el-input
                    v-model="accessName"
                    placeholder="请输入资产名称"
                    clearable
                    @keyup.enter="accessByName"
                    @clear="clearAccess"
                  >
                    <template #append>
                      <el-button @click="accessByName" :loading="accessing">
                        <el-icon><Edit /></el-icon>
                      </el-button>
                    </template>
                  </el-input>
                </div>
              </el-col>
              
              <el-col :span="8">
                <div class="access-item">
                  <label>按编码编辑：</label>
                  <el-input
                    v-model="accessCode"
                    placeholder="请输入资产编码"
                    clearable
                    @keyup.enter="accessByCode"
                    @clear="clearAccess"
                  >
                    <template #append>
                      <el-button @click="accessByCode" :loading="accessing">
                        <el-icon><Edit /></el-icon>
                      </el-button>
                    </template>
                  </el-input>
                </div>
              </el-col>
            </el-row>
            
            <!-- 访问结果 -->
            <div v-if="accessResults.length > 0" class="access-results">
              <h4>找到的资产：</h4>
              <el-table :data="accessResults" stripe style="width: 100%">
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="name" label="资产名称" />
                <el-table-column prop="code" label="编码" width="120" />
                <el-table-column prop="category" label="分类" width="100" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="getStatusType(scope.row.status)">
                      {{ scope.row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                  <template #default="scope">
                    <el-button type="warning" size="small" @click="editAsset(scope.row)">
                      编辑
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            
            <!-- 无结果提示 -->
            <div v-else-if="hasAccessed && accessResults.length === 0" class="no-results">
              <el-empty description="未找到相关资产" />
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 编辑表单页面 - 当有ID参数时显示 -->
    <el-card v-else class="form-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>编辑资产</span>
          <div class="header-actions">
            <el-button @click="handleBack">返回</el-button>
          </div>
        </div>
      </template>
      
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="asset-form"
        v-loading="loading"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资产名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入资产名称" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入资产编码" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资产分类" prop="category">
              <el-select v-model="form.category" placeholder="请选择分类" style="width: 100%">
                <el-option v-for="item in categories" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="正常" value="正常" />
                <el-option label="维护中" value="维护中" />
                <el-option label="报废" value="报废" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资产价值" prop="value">
              <el-input-number
                v-model="form.value"
                :min="0"
                :precision="2"
                style="width: 100%"
                placeholder="请输入资产价值"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="位置" prop="location">
              <el-input v-model="form.location" placeholder="请输入资产位置" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="购买日期" prop="purchaseDate">
              <el-date-picker
                v-model="form.purchaseDate"
                type="date"
                placeholder="请选择购买日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplier">
              <el-input v-model="form.supplier" placeholder="请输入供应商" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="资产描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入资产描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <div class="form-actions">
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            保存
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Document, Tools, Location, Money, List, Plus } from '@element-plus/icons-vue'
import { assetApi, categoryApi } from '@/api'
import { AssetStatusTextToCode, AssetStatusCodeToText } from '@/utils/status'

const router = useRouter()
const route = useRoute()

// 判断是否有ID参数
const hasId = computed(() => {
  return !!route.params.id
})

// 访问相关变量
const accessId = ref('')
const accessName = ref('')
const accessCode = ref('')
const accessing = ref(false)
const accessResults = ref<any[]>([])
const hasAccessed = ref(false)

// 动态分类选项供下拉与查询使用
const categories = ref<any[]>([])
const loadCategories = async () => {
  const list: any = await categoryApi.getAll()
  categories.value = (list || []).map((c: any) => ({ label: c.name, value: c.id }))
}

// 表单数据
const form = reactive({
  id: null,
  name: '',
  code: '',
  category: '',
  status: '正常',
  value: 0,
  location: '',
  purchaseDate: '',
  supplier: '',
  description: '',
  remark: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入资产名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入资产编码', trigger: 'blur' },
    { pattern: /^[A-Z0-9_-]+$/, message: '编码只能包含大写字母、数字、下划线和横线', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择资产分类', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  value: [
    { required: true, message: '请输入资产价值', trigger: 'blur' },
    { type: 'number', min: 0, message: '价值必须大于等于0', trigger: 'blur' }
  ],
  purchaseDate: [
    { required: true, message: '请选择购买日期', trigger: 'change' }
  ]
}

// 状态
const loading = ref(false)
const submitting = ref(false)
const formRef = ref()

// 获取资产详情
const getAssetDetail = async (id: number) => {
  loading.value = true
  try {
    const res: any = await assetApi.getDetail(id)
    Object.assign(form, {
      id: res.id,
      name: res.name,
      code: res.code,
      category: res.categoryId,
      status: AssetStatusCodeToText[res.status] || '正常',
      value: res.value,
      location: res.location,
      purchaseDate: res.purchaseDate,
      supplier: res.supplier || '',
      description: res.description,
      remark: res.remark
    })
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    await assetApi.update(form.id!, {
      ...form,
      code: form.code,
      categoryId: form.category,
      status: AssetStatusTextToCode[form.status]
    })
    
    ElMessage.success('保存成功')
    router.push('/asset/list')
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

// 取消
const handleCancel = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要取消编辑吗？未保存的内容将丢失。',
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '继续编辑',
        type: 'warning'
      }
    )
    router.back()
  } catch {
    // 用户选择继续编辑
  }
}

// 返回
const handleBack = () => {
  router.back()
}

// 重置表单
const handleReset = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要重置表单吗？所有修改将丢失。',
      '确认重置',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    if (formRef.value) {
      formRef.value.resetFields()
    }
    ElMessage.success('表单已重置')
  } catch {
    // 用户取消
  }
}

// 跳转到资产列表
const goToAssetList = () => {
  router.push('/asset/list')
}

// 跳转到添加资产
const goToAddAsset = () => {
  router.push('/asset/add')
}

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case '正常':
      return 'success'
    case '维护中':
      return 'warning'
    case '报废':
      return 'danger'
    default:
      return 'info'
  }
}

// 按ID访问
const accessById = () => {
  const idStr = accessId.value.trim()
  if (!idStr) {
    ElMessage.warning('请输入资产ID')
    return
  }
  const id = parseInt(idStr)
  if (isNaN(id)) {
    ElMessage.warning('资产ID必须为数字')
    return
  }
  // 直接路由跳转，组件会根据新 id 自动加载详情
  router.replace(`/asset/edit/${id}`)
}

// 按名称访问
const accessByName = async () => {
  const keyword = accessName.value.trim()
  if (!keyword) {
    ElMessage.warning('请输入资产名称')
    return
  }

  accessing.value = true
  hasAccessed.value = true

  try {
    const res: any = await assetApi.getList({ name: keyword, page: 1, size: 20 })
    const records = res?.list || []
    accessResults.value = records.map((n: any) => ({
      id: n.id,
      name: n.name,
      code: n.code,
      category: n.categoryId,
      status: AssetStatusCodeToText[n.status] || n.status
    }))

    if (accessResults.value.length > 0) {
      ElMessage.success(`找到 ${accessResults.value.length} 个相关资产`)
    } else {
      ElMessage.warning('未找到相关资产')
    }
  } catch (error) {
    ElMessage.error('访问失败，请重试')
  } finally {
    accessing.value = false
  }
}

// 按编码访问
const accessByCode = async () => {
  const keyword = accessCode.value.trim()
  if (!keyword) {
    ElMessage.warning('请输入资产编码')
    return
  }

  accessing.value = true
  hasAccessed.value = true

  try {
    // 先查询一页数据，再在前端按编码过滤
    const res: any = await assetApi.getList({ page: 1, size: 50 })
    const records = res?.list || []
    const upper = keyword.toUpperCase()
    const filtered = records.filter((n: any) => (n.code || '').toUpperCase().includes(upper))

    accessResults.value = filtered.map((n: any) => ({
      id: n.id,
      name: n.name,
      code: n.code,
      category: n.categoryId,
      status: AssetStatusCodeToText[n.status] || n.status
    }))

    if (accessResults.value.length > 0) {
      ElMessage.success(`找到 ${accessResults.value.length} 个相关资产`)
    } else {
      ElMessage.warning('未找到相关资产')
    }
  } catch (error) {
    ElMessage.error('访问失败，请重试')
  } finally {
    accessing.value = false
  }
}

// 清除访问结果
const clearAccess = () => {
  accessResults.value = []
  hasAccessed.value = false
}

// 编辑资产
const editAsset = (asset: any) => {
  if (!asset.id) {
    ElMessage.warning('无法获取资产ID')
    return
  }
  router.replace(`/asset/edit/${asset.id}`)
}

// 查看资产
const viewAsset = (asset: any) => {
  router.push(`/asset/detail/${asset.id}`)
}

onMounted(() => {
  loadCategories()
  if (hasId.value) {
    getAssetDetail(parseInt(route.params.id as string))
  }
})

// 监听路由参数变化
watch(() => route.params.id, (newId) => {
  if (newId) {
    getAssetDetail(parseInt(newId as string))
  } else {
    // 重置表单
    Object.assign(form, {
      id: null,
      name: '',
      code: '',
      category: '',
      status: '正常',
      value: 0,
      location: '',
      purchaseDate: '',
      supplier: '',
      description: '',
      remark: ''
    })
  }
})
</script>

<style scoped>
.asset-edit {
  padding: 20px;
}

.welcome-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 60vh;
}

.quick-access-section {
  width: 100%;
  max-width: 800px;
}

.access-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.access-content {
  padding: 20px;
}

.access-item {
  margin-bottom: 20px;
}

.access-item label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: var(--text-color);
  font-size: 14px;
}

.access-item .el-input {
  width: 100%;
}

.access-item .el-button {
  margin-left: 10px;
}

.access-results {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid var(--border-color);
}

.access-results h4 {
  margin-bottom: 15px;
  color: var(--text-color);
}

.no-results {
  margin-top: 20px;
  text-align: center;
}

.recent-assets {
  margin-bottom: 20px;
}

.recent-card {
  max-width: 800px;
  width: 100%;
}

.recent-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recent-card .header-actions {
  display: flex;
  gap: 10px;
}

.form-card {
  margin-bottom: 20px;
}

.form-actions {
  text-align: center;
  padding: 20px 0;
  border-top: 1px solid #ebeef5;
  margin-top: 30px;
}

@media (max-width: 768px) {
  .asset-edit {
    padding: 10px;
  }
  
  .welcome-actions {
    flex-direction: column;
  }
  
  .form-actions {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
}
</style> 